package com.xiaoyu.binaryTree;

/**
 * @program: DS_and_A
 * @description: 相同的树
 *
 * 给你两棵二叉树的根节点 p 和 q ，编写一个函数来检验这两棵树是否相同。
 *
 * 如果两个树在结构上相同，并且节点具有相同的值，则认为它们是相同的
 *
 * @author: YuWenYi
 * @create: 2021-05-15 09:04
 **/
public class IsSameTree_100 {
    //这就是深度优先算法,没想到自己误打误撞写了出来
    public static boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null){
            return true;
        }
        //由于上面的判断条件,能走到这里,说明p和q已经不可能同时为空,因此下面的判断就是q和p只有一个为空的情况
        if (p == null || q == null || p.val != q.val){
            return false;
        }

        //下面的所有判断可以化简成一行: return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
        boolean leftJudge = isSameTree(p.left, q.left);
        if (!leftJudge){
            return false;
        }
  /*      boolean rightJudge = isSameTree(p.right, q.right);
        if (!rightJudge) {
            return false;
        }
        return true;*/
        //上面的那些判断等价于
        return isSameTree(p.right, q.right);
    }


    public static void main(String[] args) {
        TreeNode node2 = new TreeNode(3);
        TreeNode node1 = new TreeNode(2,node2,new TreeNode(4));
        TreeNode left = new TreeNode(5,new TreeNode(6),new TreeNode(7));
        TreeNode root = new TreeNode(1,left,node1);


        TreeNode node22 = new TreeNode(3);
        TreeNode node12 = new TreeNode(2,node22,new TreeNode(4));
        TreeNode left2 = new TreeNode(5,new TreeNode(6),new TreeNode(7));
        TreeNode root2 = new TreeNode(1,left2,node12);

        System.out.println(isSameTree(root,root2));

    }


}
